//
//  SCSearchPopUpView.m
//  Assembly
//
//  Created by 葛悦彣 on 2023/11/13.
//

#import "SCSearchPopUpView.h"
#import "UIScrollView+EmptyDataSet.h"

@interface SCSearchPopUpView ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIGestureRecognizerDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


@property (nonatomic ,strong) UIView * makeView;
@property (nonatomic ,strong) void(^Block)(NSString * str);
@property (nonatomic ,strong) UILabel * TitleLab;
@property (nonatomic ,strong) UIButton * exitBtn;
@property (nonatomic ,strong) UITextField * searchField;
@property (nonatomic ,strong) UIView * searchView;
@property (nonatomic ,assign) BOOL isopen;
@property (nonatomic ,strong) UIButton * qxBtn;
@property (nonatomic ,strong) NSString * SearchTitle;
@property (nonatomic ,strong) UILabel * SearchPlaceholder;
@property (nonatomic ,strong) UITableView * tableview;
@property (nonatomic ,strong) NSArray <NSString *>* StringArray;
@property (nonatomic ,strong) NSMutableArray <NSString *>* NewStringArray;
@property (nonatomic ,strong) UIButton * qkBtn;
@end

@implementation SCSearchPopUpView
- (NSMutableArray<NSString *> *)NewStringArray {
    if(!_NewStringArray){
        _NewStringArray = [NSMutableArray array];
        [_NewStringArray addObjectsFromArray:self.StringArray];
    }
    return _NewStringArray;
}
+ (instancetype)ShowViewWithTitle:(NSString *)title andSearchTitle:(NSString *)SearchTitle andStringArray:(NSArray <NSString *>*)StringArray andBlock:(void(^)(NSString * str))block{
    
    SCSearchPopUpView *  view = [SCSearchPopUpView new];
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [[DTKTool getCurrentVC].view addSubview:view];
    
    [view viewWithTitle:title andSearchTitle:SearchTitle andStringArray:StringArray andBlock:block];
    
    return view;
}
- (void)viewWithTitle:(NSString *)title andSearchTitle:(NSString *)SearchTitle andStringArray:(NSArray <NSString *>*)StringArray andBlock:(void(^)(NSString * str))block{
    
//    if(StringArray.count < 1){
//        [[DTKTool getCurrentVC].view showWarning:@"暂无可更换配件"];
//        [self dismiss];
//        return;
//    }
    
    UIView * makeView = [UIView new];
    self.Block = block;
    
    self.StringArray = StringArray;
    self.SearchTitle = SearchTitle;
    self.makeView = makeView;
    makeView.backgroundColor = KcolorHex(@"#F0F6FD");
    makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH,  kwt(520) + KSafeAreaBottomHeight);
    [self addSubview:makeView];
    [DTKTool BFYJ:kwt(15) andView:makeView andCorner:UIRectCornerTopLeft|UIRectCornerTopRight andSize: CGRectMake(0, 0 ,SCREEN_WIDTH, kwt(520) + KSafeAreaBottomHeight)];
    MJWeakSelf
    makeView.addClickBlock(^(){
        [weakSelf noClick];
    });

    
    self.addClickBlock(^(){
        [weakSelf dismiss];
    });
    
    UILabel * TitleLab = [DTKTool labelWithText:title andFont:kCFont(17) andTextColor:KcolorHex(@"#1E2425")];
    self.TitleLab = TitleLab;
    [self.makeView addSubview:TitleLab];
    [TitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.offset(kwt(17));
        make.top.offset(kwt(16));
    }];
    
    UIButton * exitBtn = [UIButton buttonWithType:0];
    self.exitBtn = exitBtn;
    exitBtn.addBackgroundimg([UIImage imageNamed:@"delete_bullet_box"]).addTarget(self,@selector(dismiss));
    [self.makeView addSubview:exitBtn];
    [exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kwt(17));
        make.centerY.equalTo(TitleLab);
        make.right.offset(kwt(-17));
    }];
    
  
    UIView * searchView = [UIView new];
    searchView.addClickBlock(^(){
        [weakSelf searchViewClick];
    });
    self.searchView = searchView;
    searchView.backgroundColor = UIColor.whiteColor;
    [DTKTool YJ:kwt(22) andView:searchView];
    searchView.frame = CGRectMake(kwt(12), kwt(50), kwt(350), kwt(44));
    [self.makeView addSubview:searchView];
    
    UIImageView * searchimg = kimageView(@"search_for");
    [searchView addSubview:searchimg];
    [searchimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.height.offset(kwt(17));
        make.left.offset(kwt(10));
    }];
    
    UILabel * SearchPlaceholder = [DTKTool labelWithText:SearchTitle andFont:kFont(16) andTextColor:KcolorHex(@"#878D8F")];
    self.SearchPlaceholder = SearchPlaceholder;
    [searchView addSubview:SearchPlaceholder];
    [SearchPlaceholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(45));
    }];
    
    [self.makeView addSubview:self.tableview];
  
    [weakSelf show];
   
    
}

- (UITableView *)tableview{
    if(!_tableview){
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kwt(110), SCREEN_WIDTH, kwt(410)) style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.emptyDataSetSource = self;
        _tableview.emptyDataSetDelegate = self;
        if (@available(iOS 11.0, *)) {
            _tableview.estimatedRowHeight = 0;
            _tableview.estimatedSectionHeaderHeight = 0;
            _tableview.estimatedSectionFooterHeight = 0;
            _tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableview.sectionHeaderTopPadding = 0;
            _tableview.fillerRowHeight = 0;
        }
        _tableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableview.sectionHeaderHeight = 0.01;
        _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableview.sectionFooterHeight = 0.01;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor = UIColor.whiteColor;
    }
    return _tableview;
}

-(BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return NO;
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    //加入你自定义的view
    UIView * noView = [UIView new];
//    UIView * noView2 = [UIView new];
//    [noView addSubview:noView2];
//    [noView2 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.offset(0);
//        make.height.offset(kwt(200));
//    }];
//    noView2.backgroundColor = UIColor.whiteColor;
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    if(self.searchField.text.length > 0){
        noTitleLab.text = @"未找到结果~";
    }
    noTitleLab.font = kFont(16);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#878D8F"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(kwt(17));
    }];

    return noView;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView*)scrollView {
    return -kwt(220);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(self.searchField.text.length < 1 && self.isopen ){
        return 0;
    }
    return self.NewStringArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kwt(48);
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    SCSearchPopUpTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SCSearchPopUpTableViewCell"];
    if (cell == nil) {
        cell = [[SCSearchPopUpTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SCSearchPopUpTableViewCell"];
    }
    cell.name = self.NewStringArray[indexPath.row];
    cell.backgroundColor = UIColor.whiteColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MJWeakSelf
    cell.clickBlock = ^(NSString * _Nonnull str) {
        if(weakSelf.Block){
            weakSelf.Block(str);
            [weakSelf dismiss];
        }
    };
    return cell;
}


- (void)searchViewClick{
    if(self.isopen == NO){
        self.isopen = YES;
        [UIView animateWithDuration:0.1 animations:^{
            self.TitleLab.hidden = YES;
            self.exitBtn.hidden = YES;
            self.tableview.frame = CGRectMake(0, kwt(82), KSCREEN_WIDTH, kwt(438));
            self.searchView.frame = CGRectMake(kwt(12), kwt(24), kwt(300), kwt(44));
        } completion:^(BOOL finished) {
            self.SearchPlaceholder.hidden = YES;
            if(!self.searchField){
                UITextField * searchField = [UITextField new];
                self.searchField = searchField;
                searchField.placeholder = self.SearchTitle;
                [searchField addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
                searchField.font = kFont(16);
                searchField.textColor = KcolorHex(@"#1E2425");
                [self.searchView addSubview:searchField];
                [searchField mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.top.bottom.offset(0);
    //                make.height.offset(kwt(17));
                    make.left.offset(kwt(40));
                    make.right.offset(kwt(-40));
                }];
                
                UIButton * qkBtn = [UIButton buttonWithType:0];
                self.qkBtn = qkBtn;
                qkBtn.hidden = YES;
                qkBtn.addTarget(self,@selector(newFieldText)).addimg([UIImage imageNamed:@"delete_content"]);
                [self.searchView addSubview:qkBtn];
                [qkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.height.offset(kwt(20));
                    make.centerY.equalTo(self.searchField);
                    make.right.offset(kwt(-15));
                }];
            } else {
                self.searchField.hidden = NO;
            }
            [self.searchField becomeFirstResponder];

            if(!self.qxBtn){
                UIButton * qxBtn = [UIButton buttonWithType:0];
                self.qxBtn = qxBtn;
                qxBtn.addNormalText(@"取消").addNormalColor(KcolorHex(@"#1E2425")).addFont(kFont(16)).addTarget(self,@selector(qxBtnClick));
                [self.makeView addSubview:qxBtn];
                [qxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.height.offset(kwt(17));
                    make.width.offset(kwt(40));
                    make.centerY.equalTo(self.searchView);
                    make.right.offset(kwt(-15));
                }];
            } else {
                self.qxBtn.hidden = NO;

            }
            [self.NewStringArray removeAllObjects];
            [self.tableview reloadData];

        }];
    }
}
- (void)qxBtnClick{
    [self newFieldText];
    [self.searchField resignFirstResponder];
    
    [UIView animateWithDuration:0.1 animations:^{
        self.TitleLab.hidden = NO;
        self.exitBtn.hidden = NO;
        self.SearchPlaceholder.hidden = NO;
        self.tableview.frame = CGRectMake(0, kwt(110), KSCREEN_WIDTH, kwt(410));
        self.searchView.frame = CGRectMake(kwt(12), kwt(50), kwt(350), kwt(44));
    } completion:^(BOOL finished) {
        self.isopen = NO;
        self.qxBtn.hidden = YES;
        self.searchField.hidden = YES;
        self.NewStringArray = [[NSMutableArray alloc] initWithArray: self.StringArray];
        [self.tableview reloadData];
    }];
}
-(void)changedTextField:(UITextField *)textField
{
    if (textField.markedTextRange) {
        return;
    }
    
    if(textField.text.length > 0){///有数据
//        [self search:textField.text];
        self.qkBtn.hidden = NO;
        NSMutableArray * NewStringArray = [NSMutableArray new];
        for (NSString * str in self.StringArray) {
            if([str containsString:textField.text]){
                [NewStringArray addObject:str];
            }
        }
        self.NewStringArray = NewStringArray;
    } else {
        self.NewStringArray = [[NSMutableArray alloc] initWithArray: self.StringArray];
    }
    [self.tableview reloadData];
}
- (void)newFieldText{
    self.qkBtn.hidden = YES;
    self.searchField.text = @"";
    [self.searchField becomeFirstResponder];
    self.NewStringArray = [[NSMutableArray alloc] initWithArray: self.StringArray];
    [self.tableview reloadData];

}
- (void)noClick{
}
- (void)show {
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, SCREEN_HEIGHT - kwt(520) - KSafeAreaBottomHeight, SCREEN_WIDTH ,  kwt(520) + KSafeAreaBottomHeight);
    }];
}
- (void)dismiss{
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH,  kwt(520) + KSafeAreaBottomHeight);
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];
}
@end

@interface SCSearchPopUpTableViewCell()
@property (nonatomic ,strong) UILabel * namelab;
@end
@implementation SCSearchPopUpTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [self setupView];
    }
    return self;
}


- (void)setupView{
    
    self.backgroundColor = UIColor.clearColor;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.userInteractionEnabled = YES;
    self.contentView.userInteractionEnabled = YES;
   
    
    UILabel * namelab = [DTKTool labelWithText:@"--" andFont:kFont(16) andTextColor:KcolorHex(@"#1E2425")];
    [self.contentView addSubview:namelab];
    namelab.numberOfLines = 2;
    self.namelab = namelab;
    [namelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(17));
        make.right.offset(kwt(-17));
    }];
    
    UIView * line = [UIView new];
    line.backgroundColor = KcolorHex(@"#E1E1E1");
    [self.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.left.offset(kwt(15));
        make.right.offset(kwt(-15));
        make.height.offset(0.5);
    }];
    MJWeakSelf
    self.contentView.addClickBlock(^{
        [weakSelf click];
    });
}
- (void)setName:(NSString *)name {
    _name = name;
    self.namelab.text = name;
}
- (void)click{
    if(self.clickBlock){
        self.clickBlock(self.name);
    }
}
@end
